export function getDateTxt(date: string) {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = d.getMonth() + 1;
  const day = d.getDate();
  const hour = d.getHours();
  const minute = d.getMinutes();
  const second = d.getSeconds();
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}


// 分割字符串成数组
export const splitStrToArray = (str: string, separator: string = ",") => {
  if (!str) return [];
  return str.split(separator).filter((v) => v !== "");
};

/**
 * 字符串转金额
 * @param {string} str
 * @param {boolean} useThousandth 是否转换千分位
 * @returns {string}
 */
export const formatMoney = (str: string | number, useThousandth: boolean = false) => {
  if (!str || str == "0") return "0.00";
  // 考虑非数字情况
  if (isNaN(parseFloat(str + ""))) return "-.--";
  let mony = parseFloat(str + "").toFixed(2);
  if (useThousandth) {
    mony = mony.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }
  return mony;
};

/**
 * 普通对象转 url 参数
 */
export const obj2urlParams = (obj: any) => {
  return Object.keys(obj)
    .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`)
    .join("&");
};

// 获取随机字符串id (不能是数字开头)
export function getUUID() {
  return Math.random().toString(36).substring(2);
}

// 获取url参数
export const getQueryString = (name: string) => {
  try {
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    const r = reg.exec(window.location.search.substring(1));
    if (r != null) {
      return decodeURIComponent(r[2]);
    }
    return null;
  } catch (error) {
    return null;
  }
};

// 将url参数转为对象
export const getQueryObject = (url: string) => {
  try {
    url = url ?? window.location.href;
    const search = url.substring(url.lastIndexOf("?") + 1);
    const obj: any = {};
    const reg = /[^?&=]+=(?:[^?&=]*)/g;  // 匹配类似a=1&b=2的字符串
    search.replace(reg, (rs, $1, $2) => {
      const name = decodeURIComponent($1);
      let val = decodeURIComponent($2);
      val = String(val);
      obj[name] = val;
      return rs;
    });
    return obj;
  } catch (error) {
    return {};
  }
};
